﻿using Common.Communication;
using Common.Device.DeviceDb;
using Common.Device.Enums;
using Common.Device.Interfaces;
using Common.Tool.DataTools;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Runtime.ConstrainedExecution;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CeLiangYi.DianZuYi
{
    public class AT512SerialPort : SerialPortBase, IDianZuYi
    {
        public string Name { get; set; }
        public AT512SerialPort(UseDevice device) : base(device.port, Convert.ToInt32(device.parameter), timeout: 1000)
        {
            Name = device.name;
        }
        public Result<double> GetResistance(int channel = 1, CeLiangYiEnum.ResistanceMode mode = CeLiangYiEnum.ResistanceMode._2WR)
        {
            lock (this)
            {
                var result = new Result<double>();
                var write = new Result();
                var read = new Result<string>();
                AppendInfo(Name, $"设置自动量程");
                write = Write(CmdAutoRange);
                if (write.IsSucceed == false)
                {
                    result.IsSucceed = false;
                    result.Err = "设置自动量程失败";
                    AppendTip(Name, result.Err);
                    return result.EndTime();
                }
                Thread.Sleep(200);
                read = WriteThenRead(CmdGetRange, wait: 200);
                if (read.IsSucceed == false || string.IsNullOrEmpty(read.Value))
                {
                    result.IsSucceed = false;
                    result.Err = "设置自动量程失败";
                    AppendTip(Name, result.Err);
                    return result.EndTime();
                }
                Thread.Sleep(200);
                AppendInfo(Name, $"读取当前电阻");
                read = WriteThenRead(CmdFetch, wait: 200);
                if (read.IsSucceed == false || !double.TryParse(read.Value, out double R))
                {
                    result.IsSucceed = false;
                    result.Err = "读取当前电阻失败";
                    AppendTip(Name, result.Err);
                    return result.EndTime();
                }
                result.Value = R;
                AppendInfo(Name, DataConvert.ToUnit(R, "F3") + "Ω");
                return result.EndTime();
            }
        }


        string CmdFetch => "FETCH?\n";
        string CmdAutoRange => "FUNC:RANG:AUTO ON\n";
        string CmdGetRange => "FUNC:RANG?\n";
    }
}
